package com.itjiange.controller;

import cn.hutool.crypto.SecureUtil;
import com.itjiange.codesandbox.impl.JavaDockerCodeSandbox;
import com.itjiange.codesandbox.impl.JavaNativeCodeSandBox;
import com.itjiange.model.ExecuteCodeRequest;
import com.itjiange.model.ExecuteCodeResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author ItJianGe
 * @data 2024/3/26 8:25
 */
@RestController
@RequestMapping("/api")
public class MainController {

    public static final String accessKey = "yijian";
    public static final String secretKey = "jiange";

    @Resource
    private JavaNativeCodeSandBox javaNativeCodeSandBox;

    @Resource
    private JavaDockerCodeSandbox javaDockerCodeSandbox;

    @GetMapping("/ok")
    public String getOk() {
        return "ok";
    }

    @PostMapping("/execute_code")
    public ExecuteCodeResponse getCodeSandBox(@RequestBody ExecuteCodeRequest executeCodeRequest,
                                              HttpServletRequest request) {
        String checkAccessKey = request.getHeader("accessKey");
        String checkSecretKey = request.getHeader("secretKey");

        if (!accessKey.equals(checkAccessKey) || !SecureUtil.md5(secretKey).equals(checkSecretKey)) {
            return new ExecuteCodeResponse();
        }

        if (executeCodeRequest == null) {
            ExecuteCodeResponse executeCodeResponse = new ExecuteCodeResponse();
            executeCodeResponse.setMessage("传入参数有误");
            return executeCodeResponse;
        }
        return javaNativeCodeSandBox.executeCode(executeCodeRequest);
    }
}
